package com.nerve.android.cloudoffice.service.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;

import com.alibaba.fastjson.JSON;
import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.domain.Message;
import com.nerve.android.cloudoffice.domain.db.MessageDao;
import com.nerve.android.cloudoffice.service.NetService;

@SuppressLint("UseSparseArrays")
public final class MessageData {
	
	private final static String URL = Const.HOST + "message/";
	
	private static List<Message> messageList = new ArrayList<Message>();
	
	private static MessageDao messageDao;
	
	private static MessageDao getDao(){
		if(messageDao == null)
			messageDao = new MessageDao(OfficeApplication.context);
		
		return messageDao;
	}
	
	/**
	 * @method name: getSessionList
	 * @description: 获取最新的会话列表，用于在列表页中显示聊天信息
	 * @return type: List<Message>
	 *
	 * @return
	 */
	public final static List<Message> getSessionList(int uid){
		MessageDao dao = new MessageDao(OfficeApplication.context);
		String where = "fromId=" + uid +" or toId=" + uid + " order by _id asc";
		Cursor cursor = dao.query(
				"(select * from MESSAGE_ where " + where +") as m1", 
				dao.getColumns(), 
				null, 
				null, 
				"groupId", 
				null, 
				"_id desc"
				);
		
		List<Message> list = dao.buildToList(cursor);
		//List<Message> list = dao.getList("fromId=" + uid +" or toId=" + uid, null, "groupId", null, "addDate desc");
		return list;
	}
	
	/**
	 * @method name: loadMessageFromServer
	 * @description: 从服务器中下载与id相关的未读聊天信息
	 * @return type: Reply
	 *
	 * @param id
	 * @return
	 */
	public final static Reply loadMessageFromServer(int id){
		Reply re = NetService.get(URL + "list.htm?id=" + id);
		
		List<Message> ml = null;
		if(!re.isError()){
			try{
				ml = JSON.parseArray(re.getMessage().toString(), Message.class);
				
				Const.log("得到的最新消息长度：" + ml.size());
				
				saveMessage(ml, id);
			}catch(Exception e){
				Const.log("在获取远程消息时出错了：" + e.toString() + ", " + e.getMessage());
			}
		}
		
		if(ml == null)
			ml = new ArrayList<Message>();
		
		Const.log("loadMessageFromServer 方式完成，最新的messageList 长度为：" + messageList.size());
		
		re.setMessage(ml.size());
		return re;
	}
	
	private synchronized final static void saveMessage(List<Message> ml, int uid){
		fixMessage(ml, uid);
		
		MessageDao dao = new MessageDao(OfficeApplication.context);
		for(Message m:ml){
			dao.insert(buildMessageCV(m));
			
			//从0开始增加，保证最新的消息一直在最前
			messageList.add(0, m);
			
			Const.log("save to db:" + m.toString());
		}
	}
	
	/**
	 * @method name: fixMessage
	 * @description: 先对消息作一些处理
	 * @return type: void
	 *
	 */
	private final static void fixMessage(List<Message> ml, int uid){
		for(Message m:ml){
			String name = m.getFromUser();
			String temp[] = name.split(" ");
			m.setFromId(Integer.valueOf(temp[0]));
			m.setFromUser(temp[1]);
			
			name = m.getToUser();
			temp = name.split(" ");
			m.setToId(Integer.valueOf(temp[0]));
			m.setToUser(temp[1]);
			
			//设置非当前登录用户id 为 groupid，方便以后查询
			m.setGroupId(m.getFromId() == uid? m.getToId():m.getFromId());
		}
	}
	
	private final static ContentValues buildMessageCV(Message m){
		ContentValues cv = new ContentValues();
		cv.put("fromUser", m.getFromUser());
		cv.put("fromId", m.getFromId());
		cv.put("toUser", m.getToUser());
		cv.put("toId", m.getToId());
		cv.put("message", m.getMessage());
		cv.put("groupId", m.getGroupId());
		cv.put("addDate", m.getJoinDate().getTime());
		cv.put("hasRead", m.isRead());
		
		return cv;
	}
	
	/**
	 * @method name: getMessageById
	 * @description: 根据聊天对象id获取消息
	 * @return type: List<Message>
	 *
	 * @param uid
	 * @param targetId
	 * @return
	 */
	public final static List<Message> getLastedMessage(int targetId){
		List<Message> list = new ArrayList<Message>();
		synchronized (messageList) {
			Message m = null;
			for(int i=0;i<messageList.size();i++){
				m = messageList.get(i);
				if(m.getFromId() == targetId){
					list.add(m);
					messageList.remove(m);
				}
			}
		}
		
		return list;
	}
	
	/**
	 * @method name: getMessageRecord
	 * @description: 从数据库中获取已经保存的聊天记录
	 * @return type: List<Message>
	 *	
	 * @param uid	当前登录id
	 * @param targetId	聊天对象id
	 * @return
	 */
	public final static List<Message> getMessageRecord(int uid, int targetId){
		MessageDao dao = new MessageDao(OfficeApplication.context);
		
		return dao.getList(
				"groupId = " +targetId+ " and (fromId=" + uid +" or toId=" + uid + ")", 
				null, 
				null, 
				null, 
				"addDate"
				);
	}
	
	
	/**
	 * @method name: sendMessage
	 * @description: 发送短消息
	 * @return type: Reply
	 *
	 * @param fromId
	 * @param toId
	 * @param message
	 * @return
	 */
	public final static Reply sendMessage(int fromId, int toId, String message){
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", fromId+"");
		map.put("toId", toId+"");
		map.put("message", message);
		
		Reply re = NetService.post(URL + "send.htm", map);
		
		return re;
	}
	
	
	public final static void saveMessageToDB(Message m){
		getDao().insert(buildMessageCV(m));
		
		Const.log("保存到数据库中成功：" + m.toString());
	}
}